package com.icinfo.cloud.provider.common.utils;

import com.icinfo.framework.mybatis.mapper.util.StringUtil;
import gui.ava.html.image.generator.HtmlImageGenerator;
import org.apache.commons.codec.binary.Base64;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

/**
 * 描述：pdf转图片工具类
 *
 * @author shishengyao
 * @description
 * @date 2022/8/11
 */
public class PdfTransferImageUtil {
    /**
     * dpi越大转换后越清晰，相对转换速度越慢
     */
    private static final Integer DPI = 100;

    /**
     * 转换后的图片类型
     */
    private static final String IMG_TYPE = "png";

    /**
     * 描述：pdf转图片（仅支持一页，多页会有文件丢失）
     *
     * @param pdfUrl pdf格式的url
     * @author shishengyao
     * @date 2022/08/17
     */
    public static String pdfTransImage(String pdfUrl) {
        if (StringUtil.isEmpty(pdfUrl)){
            return "";
        }
        String imageBase64Str = "";
        try {
            URL url = new URL(pdfUrl);
            URLConnection connection = url.openConnection();
            InputStream inputStream = connection.getInputStream();
            PDDocument doc = PDDocument.load(inputStream);
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            for (int i = 0; i < pageCount; i++) {
                BufferedImage image = renderer.renderImageWithDPI(i, 296);
                //image = getGrayPicture(image);
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                ImageIO.write(image, IMG_TYPE, outputStream);
                byte[] bytes = Base64.encodeBase64(outputStream.toByteArray());
                outputStream.flush();
                outputStream.close();
                imageBase64Str = new String(bytes);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "data:image/png;base64," + imageBase64Str;
    }


    /**
     * 描述：pdf转灰色图片（仅支持一页，多页会有文件丢失）
     *
     * @param pdfUrl pdf格式的url
     * @author shishengyao
     * @date 2022/08/17
     */
    public static String pdfTransGrayImage(String pdfUrl) {
        if (StringUtil.isEmpty(pdfUrl)){
            return "";
        }
        String imageBase64Str = "";
        try {
            URL url = new URL(pdfUrl);
            URLConnection connection = url.openConnection();
            InputStream inputStream = connection.getInputStream();
            PDDocument doc = PDDocument.load(inputStream);
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            for (int i = 0; i < pageCount; i++) {
                BufferedImage image = renderer.renderImageWithDPI(i, 296);
                image = getGrayPicture(image);
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                ImageIO.write(image, IMG_TYPE, outputStream);
                byte[] bytes = Base64.encodeBase64(outputStream.toByteArray());
                outputStream.flush();
                outputStream.close();
                imageBase64Str = new String(bytes);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "data:image/png;base64," + imageBase64Str;
    }

public static String getImage( String htmlstr ){
    HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
    imageGenerator.loadHtml(htmlstr);
    BufferedImage bufferedImage = getGrayPicture(imageGenerator.getBufferedImage());
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {
        ImageIO.write(bufferedImage, "jpg", outputStream);
        String base64Img = Base64.encodeBase64String(outputStream.toByteArray());
        String res = "data:image/jpg;base64," + base64Img.toString();
       return res;

    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if(outputStream != null){
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return  "";
}
    public static BufferedImage getGrayPicture(BufferedImage originalImage)
    {
        BufferedImage grayPicture;
        int imageWidth = originalImage.getWidth();
        int imageHeight = originalImage.getHeight();

        grayPicture = new BufferedImage(imageWidth, imageHeight,
                BufferedImage.TYPE_INT_RGB);
        ColorConvertOp cco = new ColorConvertOp(ColorSpace
                .getInstance(ColorSpace.CS_GRAY), null);
        cco.filter(originalImage, grayPicture);
        return grayPicture;
    }
}
